package com.tgq.demo.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tgq.demo.common.Result;
import com.tgq.demo.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tgq.demo.service.IUserService;
import com.tgq.demo.entity.User;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 陶国庆
 * @since 2023-01-03
 */
@RestController
@RequestMapping("/user")
@Tag(name = "user-controller",description = "用户管理")
public class UserController {

    @Resource
    private IUserService userService;   //导service包

    @PostMapping
    @ApiOperation("保存用户信息")
    public Result save(@RequestBody User user) {
        //新增或者更新
        return Result.success(userService.saveOrUpdate(user));
    }
    @DeleteMapping("/{id}")
    @ApiOperation("删除单个用户信息")
    //删除
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    @GetMapping("/username/{username}")
    @ApiOperation("根据用户名获取用户信息")
    //根据username获取用户信息
    public Result Getusername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }

    @PostMapping("/del/batch")
    @ApiOperation("删除多个用户信息")
    public Result deleteBatch(@RequestBody List<Integer> ids){  //[1,2,3]
        return Result.success(userService.removeByIds(ids));
    }

    @GetMapping
    @ApiOperation("查询所有信息")
    //查询所有
    public Result findAll() {
        return Result.success(userService.list());
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户信息")
    //根据id查询
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    //分页
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String nickname) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        if (!"".equals(nickname)) {
            queryWrapper.like("nickname",nickname);
        }
        queryWrapper.orderByDesc("id");
        //获取当前用户信息
        User currentUser = TokenUtils.getCurrentUser();
        String nickname1 = currentUser.getNickname();
        System.out.println("当前用户============="+nickname1);
        return Result.success(userService.page(new Page<>(pageNum, pageSize),queryWrapper));
    }

    /**
     * excel 导出接口
     */
    @GetMapping("/export")
    @ApiOperation("导出用户信息")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查询所有数据
        List<User> list = userService.list();
        //通过工具类创建writer写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + “/用户信息.xlsx”);
        //在内存操作写出浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("username","用户名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("nickname","昵称");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("createTime","创建时间");
        writer.addHeaderAlias("avatarUrl","头像");

        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        //创建一个输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();        //关闭输出流
        writer.close();
    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    @ApiOperation("导入用户信息")
    public Result imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("用户名","username");
        reader.addHeaderAlias("密码","password");
        reader.addHeaderAlias("昵称","nickname");
        reader.addHeaderAlias("邮箱","email");
        reader.addHeaderAlias("电话","phone");
        reader.addHeaderAlias("地址","address");
//        reader.addHeaderAlias("创建时间","createTime");
        reader.addHeaderAlias("头像","avatarUrl");

        List<User> list = reader.readAll(User.class);
        System.out.println(list);
        userService.saveBatch(list);
        return Result.success();
    }

}

